package com.neuedu.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Component  //交给IOC容器管理
public class AliOSSUtils {
    //原始写法
//    private String endpoint = "https://oss-cn-beijing.aliyuncs.com";
//    private String accessKeyId = "LTAI4GCH1vX6DKqJWxd6nEuW";
//    private String accessKeySecret = "yBshYweHOpqDuhCArrVHwIiBKpyqSL";
//    private String bucketName = "web-hmgzy";

    //配置文件 注入
//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;
//    @Value("${aliyun.oss.bucketName}")
//    private String bucketName;

    //再次优化  使用@ConfigurationProperties注解，实体封装参数，利用get方法获得。
    @Autowired
    AliyunProperties aliyunProperties;
    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile file) throws Exception {
        //获取阿里云OSS参数
        String endpoint = aliyunProperties.getEndpoint();
        String bucketName = aliyunProperties.getBucketName();

        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString().replace("-","") + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        //采用配置变量的形式，获取accessKeyId&accessKeySecret
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        ossClient.putObject(bucketName, fileName, inputStream);

        //文件访问路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}
